import axios from 'axios'
import store from '../.nuxt/store'
import { LOADING } from '../store/mutation-types/loading/index';
import qs from 'qs';
import { Message, MessageBox } from 'element-ui'
import { removeToken, setToken, getCookie, getLastParam } from '~/assets/js/global';
import { basicConfig } from '~/assets/js/config'

if (process.BROWSER_BUILD) {
    //添加请求拦截器
    axios.interceptors.request.use(function(config) {
        store.commit(LOADING, {
            loading: true
        });

        //配置请求参数
        config.timeout = '60000';
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded';

        if (config.url == basicConfig.baseUrl + '/adset/audience/reachestimate.do' || config.url == basicConfig.baseUrl + '/admanager/create.do') {
            config.headers['Content-Type'] = 'application/json';
        }
        if (config.url == basicConfig.baseUrl + '/assets/audience/createCustomAudience.do') {
            config.headers['Content-Type'] = 'multipart/form-data';
        }
        if (config.url == basicConfig.baseUrl + '/manager/adgroup/updateAdGroup.do' || config.url == basicConfig.baseUrl + '/admanager/google/create.do') {
            config.headers['Content-Type'] = 'application/json';
        }
        if (config.url == basicConfig.baseUrl + '/manager/google/adGroup/update/content') {
            config.headers['Content-Type'] = 'application/json';
        }
        if (config.url == basicConfig.baseUrl + '/adset/audience/targetingSuggestions.do' || config.url == basicConfig.baseUrl + '/adset/audience/google/reachEstimate.do') {
            config.headers['Content-Type'] = 'application/json';
        }

        if (config.url == basicConfig.baseUrl + '/adset/audience/createSavedAudience.do' || config.url == basicConfig.baseUrl + '/ad/cache.do') {
            config.headers['Content-Type'] = 'application/json';
        }

        if (config.url == basicConfig.baseUrl + '/assets/img/save.do' || config.url == basicConfig.baseUrl + '/manager/ad/updateAd.do') {
            config.headers['Content-Type'] = 'application/json';
        }

        if (config.url == basicConfig.baseUrl + '/adset/audience/updateSavedAudience.do' || config.url == basicConfig.baseUrl + '/manager/google/ad/update') {
            config.headers['Content-Type'] = 'application/json';
        }

        if (config.url == basicConfig.baseUrl + '/assets/audience/createLookAlikeAudience.do') {
            config.headers['Content-Type'] = 'application/json';
        }
        //为请求加上token
        var loginToken;
        if (process.BROWSER_BUILD) {
            loginToken = getCookie('token');
        }
        if (loginToken) {
            var method = config.method;
            switch (method) {
            case 'get':
                var params = config.params || {};
                params['loginToken'] = loginToken;
                break;
            case 'post':
                if (typeof config.data == 'string' || config.url == basicConfig.baseUrl + '/assets/audience/createCustomAudience.do') {
                    config.url = config.url + '?loginToken=' + loginToken;
                } else {
                    var data = config.data || {};
                    data['loginToken'] = loginToken;
                    if (config.headers['Content-Type'] != 'multipart/form-data') {
                        config.transformRequest = [function(data) {
                            data = qs.stringify(data);
                            return data;
                        }];
                    }
                }
                break;
            }
        }
        return config;
    }, function(error) {
        store.commit(LOADING, {
            loading: false
        });
        Message.error({
            message: error
        });
        return Promise.reject(error);
    });

    //添加响应拦截器
    axios.interceptors.response.use(function(response) {
        let specialUrl = getLastParam(response.config.url).split('?')[0];

        if (specialUrl == '/createCode.do') { //特殊情况：1------获取验证码
            return response;
        } else if (specialUrl == '/download') { //特殊情况：2------导出表格
            return response;
        } else if (specialUrl == '/create.do') { //特殊情况：3------创建广告
            return response;
        } else if (specialUrl == '/updatePolicyData') { //特殊情况：4------附加信息同步列表信息
            return response;
        }

        store.commit(LOADING, {
            loading: false
        });

        if (response.data && !response.data.success) {
            if (response.data.code == -2) { //token已过期
                if (process.BROWSER_BUILD) {
                    let token = getCookie('token');
                    if (token) {
                        removeToken('token');
                        MessageBox.confirm('用户信息已过期,请重新登录', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(() => {
                            let url = window.location.href.replace('http://', '');
                            url = url.replace(/[\?\&]?token=.*?\&/gi, '?').replace(/[\?\&]?token=.*/gi, '');
                            window.location.href = basicConfig.shopUrl + '?callback=' + url;
                        }).catch(() => {

                        });
                    } else {
                        let url = window.location.href.replace('http://', '');
                        url = url.replace(/[\?\&]?token=.*?\&/gi, '?').replace(/[\?\&]?token=.*/gi, '');
                        window.location.href = basicConfig.shopUrl + '?callback=' + url;
                    }
                }
                return false;
            } else if (response.data.code == -1) { //系统错误
                if (specialUrl != '/save.do') { //上传视频和图片不显示错误提示
                    Message.error({
                        message: response.data.message
                    });
                }
                return false;
            } else if (response.data.code == -11) { //新建受众不显示错误提示
                return response;
            } else if (response.data.code == -11000000 || response.data.code == -10000002) { //google的accessToken令牌失效，请刷新令牌 || 用户谷歌token令牌无效,登录
                //谷歌刷新令牌
                store.dispatch('refreshGoogle')
                    .then(response => {
                        if (response.data.success) {
                            Message.error({
                                message: '网络异常，请重试'
                            });
                        }
                    });
                return false;
            } else if (response.data.code == -11000001) { //请选择一个adwords账号操作
                return response;
            } else if (response.data.code == -10000004) { //用户的Google帐户已被删除
                Message.error({
                    message: response.data.message
                });
                return response;
            } else if (response.data.code == -10000003) { //申请经理账号并创建adwords账号
                Message.error({
                    message: response.data.message
                });
                return response;
            } else if (response.data.code == -11000005) { //您的赢店账号尚未绑定谷歌账号
                return response;
            } else {
                Message.error({
                    message: response.data.message
                });
                return false;
            }
        } else {
            return response;
        }
    }, function(error) {
        store.commit(LOADING, {
            loading: false
        });
        if (error.response) {
            switch (error.response.status) {
            case 404:
            case 502:
            case 503:
            case 400:
                Message.error({
                    message: '您请求的接口地址不存在'
                });
                break;
            }
        }
        return Promise.reject(error); // 返回接口返回的错误信息
    });
}


export default axios